<template>
  <div class="tag-selector">
    <a-card class="sticky top-0 z-10" :bordered="false" :body-style="{ padding: '1rem' }">
      <div class="flex flex-col gap-4">
        <div class="font-bold text-[1.5rem] flex justify-between items-center">
          <div>选择标签</div>
        </div>
        <a-input-search
          allow-clear
          placeholder="请输入标签代码"
          v-model:value="query.tagCode"
          @search="search"
        />
        <div>
          <a-pagination
            v-model:current="query.pageNum"
            :page-size="query.pageSize"
            :total="query.total"
            size="small"
            @change="onChange"
            responsive
            showLessItems
            showQuickJumper
            simple
          ></a-pagination>
        </div>
      </div>
    </a-card>

    <a-list
      size="small"
      :data-source="table.data"
      :loading="table.loading"
      :load-more="true"
      :pagination="false"
      class="p-2"
    >
      <template #renderItem="{ item }">
        <a-list-item
          class="cursor-pointer"
          @click="selectItem(item)"
          :class="{ active: item.tagCode === tagCode }"
        >
          <a-list-item-meta :title="item.tagCode">
            <template #description>
              {{ item.resolutionWidth }}x {{ item.resolutionHeight }}
            </template>
          </a-list-item-meta>
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>

<script setup lang="ts">
import { useQuery, useTable } from '@/hooks/table';
import { listPriceTag, type ITag } from '@/api/modules/esl/priceTag';

const query = useQuery<ITag>();
const table = useTable<ITag>();

const props = defineProps<Partial<ITag>>();

const tagCode = defineModel<string>('tagCode');
const modelValue = defineModel<ITag>('modelValue');
const emit = defineEmits(['select']);

const getTags = async () => {
  table.value.loading = true;
  const { data } = await listPriceTag(query.value);
  query.value.total = data.total;
  table.value.data = data.rows;
  table.value.loading = false;
};

const onChange = (page: number, pageSize: number) => {
  query.value.pageSize = pageSize;
  query.value.pageNum = page;
  getTags();
};
const selectItem = (tag: ITag) => {
  modelValue.value = tag;
  tagCode.value = tag.tagCode;
  emit('select', tag);
};

const search = () => {
  query.value.pageNum = 1;
  getTags();
};
onMounted(() => {
  query.value = Object.assign(query.value, props);
  getTags();
});
defineExpose<{
  loadData: () => any;
}>({
  loadData: getTags,
});
</script>

<style lang="scss" scoped>
:deep(.ant-list-item) {
  border: 1px solid transparent;
  border-radius: var(--radius);
}
.tag-selector {
  height: 100%;
  overflow-y: auto;
}
.active {
  outline: 1px solid var(--primary);
}
</style>
